#/usr/bin/python
# -*- coding:utf-8 -*- 
#
# 监控网页内容变化并邮件通知
#
import os,sys,time,httplib,datetime
import smtplib
from email.mime.text import MIMEText

sleep_second=1;
log_file = "join_qq.log"
mailto_list=["k@gmail.com","bar@hmail.com" ]
mail_host="smtp.gmail.com"
mail_user="username"
mail_pass="password"
mail_postfix="gmail.com"
http_headers = {
		,"User-Agent":"Mozilla/5.0 (Windows NT 6.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1"
		,"Referer":"http://join.qq.com/index.php?mod=job&act=news"
		,"Content-Type":"text/html; charset=utf-8"
		#,"X-Forwarded-For":fake_ip_prefix+str(random.randint(1,254)) +"."+ str(random.randint(1,254))
		}
def send_mail(to_list,sub,content):
    me=mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content)
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, to_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False

def log(msg,p=True):
	msg = '[' + str(datetime.datetime.now())+'] '+msg
	f=open(log_file,'a');
	f.write(msg+'\n');
	f.close()
	if p:
		print msg

send_mail(mailto_list, 'Site Change Monitor', 'start listening...'); 

conn = httplib.HTTPConnection("join.qq.com")
conn.request("GET", "/index.php?mod=job&act=news")
r = conn.getresponse()
wrt = r.read()
r.close()
conn.close()

while True:
	try:
		conn = httplib.HTTPConnection("join.qq.com")
		conn.request("GET", "/index.php?mod=job&act=news", http_headers)
		r = conn.getresponse()
		wrt2 = r.read()
	except Exception,data:
		print 'exception'
	finally:
		r.close()
		conn.close()
		if(wrt2 != wrt and -1 != wrt2.find('杭州')):
			wrt = wrt2
			log( 'Trigger fired!')
			send_mail(mailto_list, 'Site Change Monitor','Trigger fired!'); 
			for i in range(0,9):
				print ('\a')
				time.sleep(0.1)
		else:
			log('.'); 
		time.sleep(sleep_second)
